package com.gooluke.auth.config;

import com.gooluke.auth.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * SecurityConfig类用于配置Spring Security以保护应用程序的端点
 * 它通过定义安全过滤器链、认证管理器和密码编码器来实现
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 自动注入JwtAuthenticationFilter用于JWT验证
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    // 自动注入AuthEntryPoint用于处理未授权或未认证的访问请求
    @Autowired
    private AuthEntryPoint authEntryPoint;

    /**
     * 配置Spring Security的过滤器链
     *
     * @param http HttpSecurity实例，用于配置Web安全
     * @return SecurityFilterChain 安全过滤器链
     * @throws Exception 配置过程中可能抛出的异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 禁用跨站请求伪造（CSRF）保护，因为我们的应用不会使用session
                .csrf(AbstractHttpConfigurer::disable)
                // 配置异常处理，指定未认证或未授权时的入口点
                .exceptionHandling(exception -> exception.authenticationEntryPoint(authEntryPoint))
                // 配置会话管理，指定不创建会话
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置请求授权规则，允许所有与/auth开头的请求，其他请求需要认证
                .authorizeHttpRequests(auth -> {
                    auth.requestMatchers("/api/auth/**")
                            .permitAll()
                            .anyRequest()
                            .authenticated();
                })
                .httpBasic(Customizer.withDefaults())
                // 在UsernamePasswordAuthenticationFilter之前添加jwtAuthenticationFilter
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    /**
     * 配置认证管理器
     *
     * @param config AuthenticationConfiguration实例，用于构建认证管理器
     * @return AuthenticationManager 认证管理器
     * @throws Exception 构建过程中可能抛出的异常
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    /**
     * 配置密码编码器
     *
     * @return PasswordEncoder 密码编码器，这里使用BCrypt进行密码加密
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
